package com.pickgliss.loader
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	public class SimpleQueueLoader 
	{
		private var _lock : Boolean;
		private var _queue : Array;
		private var _loaders : Vector.<Loader>;
		private var _loaderDict :Dictionary = new Dictionary();
		private var _count : int;
		public static const USER_OVER : String = "USER_OVER";
		public function SimpleQueueLoader(count:int=3)
		{
			_queue = [];
			_loaders = new Vector.<Loader>();
			super();
			for(var i:int=0;i<count;i++)
			{
				_loaders.push(createLoader());
			}
			
		}
		
		private function createLoader() : Loader
		{
			var load : Loader = new Loader();
			_loaderDict[_count ++ ] = load;
//			load.contentLoaderInfo.addEventListener(USER_OVER, __nextHandler);
			return load;
		}
		private function __nextHandler(evt : Event): void
		{
			pushLoader((evt.currentTarget as LoaderInfo).loader);
		}
		
		public function addQueue(para : Object): void
		{
			var exist:Boolean = false;
			for each(var obj:Object in _queue)
			{
				if(para.fun == obj.fun) exist = true;
			}
			if(!exist) _queue.push(para);
			next();
		}
		
		private function next(): void
		{
			if(_loaders.length == 0)return ;
			if(_queue.length == 0)return;
			var obj : Object = _queue.shift();
			if(obj.para is ByteArray)
			{
				if((obj.para as ByteArray).length == 0)
				{
					next();
					return;
				}
					
			}
			var fun : Function = obj.fun;
			if(fun != null)fun(obj.para);fun = null;
			obj = null;
		}
		public function getLoader(): Loader
		{
			return _loaders.pop() as Loader;
		}
		public function pushLoader(loader : Loader): void
		{
			_loaders.push(loader)
			next();
		}
		public function get allLoaderInUse(): Boolean
		{
			return _loaders.length == 0;
		}
		public function dispose(): void
		{
			for(var key : String in _loaderDict)
			{
				var load : Loader = _loaderDict[key] as Loader;
				load.unload();
				load.unloadAndStop(true);
				load = null;
				_loaderDict[key] = null;
				delete _loaderDict[key];
			}
		}
	}
}